import com.google.appengine.api.images.*
import org.apache.commons.io.IOUtils
import org.apache.commons.fileupload.util.Streams
import org.apache.commons.fileupload.servlet.ServletFileUpload
import java.io.*;
import com.google.appengine.api.datastore.Entity
import com.google.appengine.api.datastore.Blob
import com.google.appengine.api.datastore.Key
import com.google.appengine.api.datastore.*
import static com.google.appengine.api.datastore.FetchOptions.Builder.*
import com.pobos.model.*


/* gets image upload. From Mr. Haki's blog - http://mrhaki.blogspot.com/2009/11/add-file-upload-support-to-groovlets-in.html */
uploads = [:]  // Store result from multipart content.
if (ServletFileUpload.isMultipartContent(request)) {
 def uploader = new ServletFileUpload()  
 def items = uploader.getItemIterator(request)
 while (items.hasNext()) {
	 def item = items.next()
	 def stream = item.openStream()
	 try {
		 if (item.formField) {  // 'Normal' form field.
			 	params[item.fieldName] = Streams.asString(stream,"UTF-8")
		 } else {
			 uploads[item.fieldName] = [
			                            name: item.name,
			                            contentType: item.contentType,
			                            data: IOUtils.toByteArray(stream)
			                            ]
	 }
	 } finally {
		 IOUtils.closeQuietly stream
	 }
 }
 
 
}


//examina uploads

try {

	def idImaxe
	
	if (uploads['imaxe']?.data && uploads['imaxe']?.data.length) {
		
		//Blob elBlob = uploads['imagen'].data as Blob
		byte[] datosImagen = uploads['imaxe'].data
		
		if (datosImagen.length < (1024*1024)) {
			
			 Image oldImage = ImagesServiceFactory.makeImage(datosImagen) 
			   
		   	 CompositeTransform cp = ImagesServiceFactory.makeCompositeTransform()
		   	 Transform resize = ImagesServiceFactory.makeResize(50,50)
		   	 cp.concatenate( resize )
		   	  
		   	 Image pic = images.applyTransform( cp, oldImage, ImagesService.OutputEncoding.valueOf("JPEG"))
			 //response.setContentType(uploads['imaxe'].contentType)
			 //sout << pic.imageData
			 
			 Blob b = new Blob(pic.imageData)		 
			
			
			Entity entity = new Entity("FotoPerfil")
			entity.nome="Unha foto"
			entity.imaxe = b
			entity.save()
			
			idImaxe = entity.key?.id
					
					
		} else {
			request.erro = "Imaxe moi grande!"
			forward '/perfil.gtpl'		
		}
		
	}	
	
		    	
	def sesion = request.getSession(true)
	def usuarioSession = sesion.getAttribute('usuario')
	
	Entity usuario = obtenUsuarioSesion(usuarioSession)
	
	//Crea perfil
	def nome = params['nome']
    def concello = params['concello']
    def parroquia = params['parroquia']
                          
                          
    //TODO: resto de campos
	Entity perfil = new Entity("Perfil")
	perfil.nome = nome
	
	if (idImaxe) {
		perfil.imaxe = idImaxe
	}
	
	perfil.usuario = usuario?.nome
	perfil.concello = concello	
	perfil.parroquia = parroquia
	perfil.numeroItems = 0
	perfil.save()
	
	usuario.perfil = perfil.key.id
	usuario.save()
	
	
	
	//Crea un paisano
	Entity paisano = new Entity("Paisano")
	paisano.perfil = perfil.key?.id
	paisano.concello = concello
	paisano.save()
	
	def concelloEntity = obtenConcello(Long.parseLong(concello))
	if (concelloEntity.paisanos) {
		int numeroPaisanos = concelloEntity.paisanos.size()
		concelloEntity.paisanos << paisano.key?.id
		concelloEntity.numeroPaisanos = ++numeroPaisanos;
	} else {
		concelloEntity.paisanos = [paisano.key?.id]
        concelloEntity.numeroPaisanos = 1
	}
	
	concelloEntity.save()
	
	
	request.mensaxe="O perfil foi creado con éxito."
	request.contido=""	
	request['perfil'] = perfil
	sesion.setAttribute('perfil',perfil)
	forward '/verPerfil.gtpl'		
			 
} catch (Exception e) {
	request.erro = "Produciuse un erro inesperado!: $e"
	forward '/perfil.gtpl'		
}


def obtenConcello(def id) {
	 //Obtiene la entity del concello
	 def key = KeyFactory.createKey(Concello.class.simpleName, id)
	 Entity concello = datastore.get(key)
	 
	 return concello
	
}


def obtenUsuarioSesion(String usuarioSesion) {
	def query = new Query(Usuario.class.simpleName)
	query.addFilter("nome", Query.FilterOperator.EQUAL, usuarioSesion)
	def preparedQuery = datastore.prepare(query)
	
	if (preparedQuery.countEntities() == 0) {
		return null;
	} else {
		if(preparedQuery.countEntities() > 1){
			return preparedQuery.asList(withLimit(1))[0]
		}else{
			return preparedQuery.asSingleEntity()
		}
	}
	
}    

